package com.soushangxing.comfyuibackendv2.config

import com.soushangxing.comfyuibackendv2.repository.FileRepository
import com.soushangxing.comfyuibackendv2.service.FileService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.time.LocalDateTime

@Component
class FileCleanupTask() {

    @Autowired
    lateinit var fileRepository: FileRepository

    @Autowired
    lateinit var fileService: FileService

    // 每天凌晨 2 点执行一次此任务
    @Scheduled(cron = "0 0 2 * * ?")
    fun cleanupOldFiles() {
        try {
            println("正在执行自动清除文件：")
            val cutoffTime = LocalDateTime.now().minusDays(1)
            val filesToDelete = fileRepository.findByCreateTimeBefore(cutoffTime)

            filesToDelete.forEach { file ->
                try {
                    fileService.removeFile(file.relativePath)
                    println("删除文件成功： ${file.relativePath}")
                } catch (e: Exception) {
                    println("删除文件失败： ${file.relativePath}, 原因: ${e.message}")
                }
            }
        } catch (e: Exception) {
            println("删除文件程序出错: ${e.message}")
        }
    }
}
